package com.zsc.edu.gateway.framework.security;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;
import java.util.Optional;

/**
 * @author Yao
 */
public class SecurityUtil {

    public static UserDetailsImpl getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            return new UserDetailsImpl();
        }
        return (UserDetailsImpl) authentication.getPrincipal();
    }

    public static void setUserInfo(UserDetailsImpl user) {
        // 重新加载用户信息并更新SecurityContext
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities())
        );
    }

    public static Optional<String> getCurrentAuditor() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication instanceof AnonymousAuthenticationToken) {
                return Optional.of("system");
            } else {
                if (authentication == null) {
                    return Optional.of("system");
                }
                UserDetailsImpl user = (UserDetailsImpl) authentication.getPrincipal();
                return Optional.of(user.getUsername());
            }
        } catch (Exception ex) {
            // log.error("get user Authentication failed: " + ex.getMessage(), ex);
            return Optional.of("system");
        }
    }

}
